﻿using System.Text;
using UnityEngine;
using UnityEditor;
public class ModelAnimationProcessor : AssetPostprocessor
{
    public void OnPreprocessModel()
    {
        var mi = assetImporter as ModelImporter;
        
        if (!mi.assetPath.EndsWith("fbx", System.StringComparison.OrdinalIgnoreCase))
            return;

        //模型
        if (!mi.assetPath.Contains("@"))
        {
            mi.animationType = ModelImporterAnimationType.Generic;
            mi.generateAnimations = ModelImporterGenerateAnimations.GenerateAnimations;
            mi.materialName = ModelImporterMaterialName.BasedOnTextureName;
            mi.materialSearch = ModelImporterMaterialSearch.RecursiveUp;
            return;
        }

        //动画
        var defClipAnims = mi.defaultClipAnimations;
        if (0 == defClipAnims.Length)
            return;
        var defClip = defClipAnims[0];
        if (defClip.firstFrame < 0)
            return;

        var name = System.IO.Path.GetFileNameWithoutExtension(mi.assetPath);
        var arr = name.Split('@');
        var modelName = arr[0];
        var animName = arr[1];

        var clip = new ModelImporterClipAnimation();
        clip.name = name;
        clip.loopTime = true;
        clip.firstFrame = defClip.firstFrame;
        clip.lastFrame = defClip.lastFrame;

        int numEvents = 4;
        AnimationEvent[] events = new AnimationEvent[numEvents];
        for (int i = 0; i < numEvents; ++i)
        {
            AnimationEvent evt = new AnimationEvent();
            evt.functionName = "OnAnimationEvent";
            evt.time = (i+1f)/(numEvents+1);
            events[i] = evt;
        }
        clip.events = events;
        
        int numClips = 2;
        ModelImporterClipAnimation[] ret = new ModelImporterClipAnimation[numClips+1];
        ret[0]=clip;
        for (int i = 0; i < numClips; ++i)
        {
            var ca = new ModelImporterClipAnimation();
            ca.name = string.Format("{0}@{1}{2}",modelName,animName,i);
            ca.firstFrame = i * clip.lastFrame / numClips;
            ca.lastFrame = (i + 1) * clip.lastFrame / numClips;
            ca.loopTime = false;
            ca.loop = false;
            ret[i + 1] = ca;
        }
        mi.clipAnimations = ret;
    }
}